/**
 * 
 */
package org.jft.datamodel.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;

import org.hibernate.Session;
import org.jft.datamodel.database.HibernateUtil;


/**
 * @author LAP
 *
 */
public class Inicilizer {
	
	private static List<String> getScripts() throws URISyntaxException {
		List<String> ret = Arrays.asList(new File(Inicilizer.class.getResource(Constants.CREATE_QUERY_PATH).toURI()).list());
		return ret;
	}
	
	private static void loadConfig() throws FileNotFoundException, IOException {
		File prop = new File("jft.prop");
		if(prop.exists() && prop.isFile()) {
			Config.getInstance().loadConfig(new FileInputStream(prop));
		}
		else {
			Config.getInstance().loadConfig(Inicilizer.class.getResourceAsStream(Constants.DEFAULT_PROPERTIES));
		}
	}
	
	public static void inicilize() {
		try {
			loadConfig();
			List<String> iter = getScripts();
			Session session = HibernateUtil.getInstance().getSessionFactory().getCurrentSession();
			session.beginTransaction();
			for (String script : iter) {
				session.createSQLQuery(ResourceLoader.getInstance().getSQLQuery(script)).executeUpdate();
			}
			session.getTransaction().commit();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
